<?php

namespace App\Models;

use App\Http\Controllers\PaymentController;
use App\Http\Controllers\WxPayController;
use App\Util\Tool;
use App\Util\Url;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Store extends Model
{
    protected $table = "c_stores";


    public function shoptypes()
    {
        return $this->hasOne('App\Models\StoreCategory', 'id', 'shop_type');
    }
    public function storder()
    {
        return $this->hasOne('App\Models\StoreOrder', 'store_id');
    }
    
    public function setDetailImagesAttribute($gallery)
    {
        if (is_array($gallery)) {
            $this->attributes['detail_images'] = json_encode($gallery);
        }
    }

    public function getDetailImagesAttribute($value)
    {
        return json_decode($value, true);
    }

    public function setImagesAttribute($gallery)
    {
        if (is_array($gallery)) {
            $this->attributes['images'] = json_encode($gallery);
        }
    }

    public function getImagesAttribute($value)
    {
        return json_decode($value, true);
    }

    public function addStore($data)
    {
        try {
            $tool = new Tool();
            DB::beginTransaction(); // 开始事务
            if (isset($data['id']) && !empty($data['id'])) { // 更新
                $redata = $this->getInfoEdit($data['id']);
                $redata->user_id = isset($data['user_id']) ? $data['user_id'] : $redata->user_id;
                $redata->shop_name = isset($data['shop_name']) ? $data['shop_name'] : $redata->shop_name;
                $redata->shop_type = isset($data['shop_type']) ? $data['shop_type'] : $redata->shop_type;
                $redata->province_id = isset($data['province_id']) ? $data['province_id'] : $redata->province_id;
                $redata->city_id = isset($data['city_id']) ? $data['city_id'] : $redata->city_id;
                $redata->district_id = isset($data['county_id']) ? $data['county_id'] : $redata->county_id;
                $redata->address = isset($data['address']) ? $data['address'] : $redata->address;
                $redata->lng = isset($data['lng']) ? $data['lng'] : $redata->lng;
                $redata->lat = isset($data['lat']) ? $data['lat'] : $redata->lat;
                $redata->phone = isset($data['phone']) ? $data['phone'] : $redata->phone;
                $redata->wechat = isset($data['wechat']) ? $data['wechat'] : $redata->wechat;
                $redata->notice = isset($data['notice']) ? $data['notice'] : $redata->notice;
                $redata->logo = isset($data['logo']) ? $data['logo'] : $redata->logo;
                $redata->business_license = isset($data['business_license']) ? $data['business_license'] : $redata->business_license;
                $redata->images = isset($data['images']) ?  $tool::handelString($data['images']) : $redata->images;
                $redata->detail_images = isset($data['detail_images']) ? $tool::handelString($data['detail_images']) : $redata->detail_images;
                $redata->introduce = isset($data['introduce']) ? $data['introduce'] : $redata->introduce;
                $redata->status = 0;
                $res = $redata->save();
            } else {
                //添加
                $this->user_id = isset($data['user_id']) ? $data['user_id'] : 0;
                $this->shop_name = isset($data['shop_name']) ? $data['shop_name'] : "";
                $this->shop_type = isset($data['shop_type']) ? $data['shop_type'] : 0;
                $this->province_id = isset($data['province_id']) ? $data['province_id'] : 0;
                $this->city_id = isset($data['city_id']) ? $data['city_id'] : 0;
                $this->district_id = isset($data['county_id']) ? $data['county_id'] : 0;
                $this->address = isset($data['address']) ? $data['address'] : "";
                $this->lng = isset($data['lng']) ? $data['lng'] : 0;
                $this->lat = isset($data['lat']) ? $data['lat'] : 0;
                $this->phone = isset($data['phone']) ? $data['phone'] : "";
                $this->wechat = isset($data['wechat']) ? $data['wechat'] : "";
                $this->notice = isset($data['notice']) ? $data['notice'] : "";
                $this->logo = isset($data['logo']) ? $data['logo'] : "";
                $this->business_license = isset($data['business_license']) ? $data['business_license'] : "";
                $this->images = isset($data['images']) ? $tool::handelString($data['images']) : "";
                $this->detail_images = isset($data['detail_images']) ? $tool::handelString($data['detail_images']) : "";
                $this->introduce = isset($data['introduce']) ? $data['introduce'] : "";
                $res = $this->save();
                $store_order_id = self::addStoreOrder($data);
            }
            if ($res) {
                //删除草稿箱
                if(isset($data['user_id'])){
                    (new StoreBak())->where([['user_id','=',$data['user_id']]])->delete();
                }
                DB::commit(); // 提交事务
                return ['store_id' => $this->id ?: $data['id'],'store_order_id'=>$store_order_id];
            } else {
                return '入驻失败';
                DB::rollback(); // 回滚事务
            }
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
    }


    /****
     * @param $param
     * @return mixed
     * 列表
     */
    public function getStoreList($param)
    {
        #经度
        $lng = $param["lng"];
        #纬度
        $lat = $param["lat"];
        #获取指定范围的数据单位km
        $distance_sea = 100;
        $where = [];
        $field = "topping";
        $asc = "DESC";
        if (isset($param['views']) && !empty($param['views'])) {  //热门推荐
            $field = "views";
            $asc = "desc";
        }
        if (isset($param['news']) && !empty($param['news'])) {  //最新入驻
            $field = "id";
            $asc = "desc";
        }
        if (isset($param['title']) && !empty($param['title'])) {  //名称
            $where[] = ['shop_name', 'like', '%' . $param['title'] . '%'];
        }
        if (isset($param['shop_type']) && !empty($param['shop_type'])) {  //分类id
            $where[] = ['shop_type', '=', $param['shop_type']];
        }
        $model = Store::where($where);
        $model->select(['*']);
        $distance = "ACOS(SIN(( $lat * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(( $lat* 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(( $lng* 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380";
        if (isset($param['is_distance']) && !empty($param['is_distance'])) {  //首页推荐
            $model->addSelect(DB::raw($distance . ' as distance'))->orderBy('distance', 'ASC');
        } else {
            $model->addSelect(DB::raw($distance . ' as distance'));
        }
        #控制范围
        $model->whereRaw($distance . "<" . $distance_sea);
        $data = $model->where([['status', '=', 1],['is_online','=',1]])->orderBy($field, $asc)->simplePaginate(15);
        $cates = new StoreCategory();
        $host = new Url();
        $tool = new Tool();
        foreach ($data as $v) {
            #计算距离
            $v->distance = sprintf("%.2f", $v->distance);
            $v->cate_name = $cates->where([['id', '=', $v->shop_type]])->value("name");
            $v->logo = $host::getHttpHost() . 'upload/' . $v->logo;
            if (isset($v->images) && !empty($v->images)) {
                if (is_array($v->images)) {
                    $im = [];
                    foreach ($v->images as  $kk=>$vv) {
                        $im[$kk] = $host::getHttpHost() . 'upload/' .trim($vv);
                    }
                    $v->images = $im;
                } else {
                    $v->images = $host::getHttpHost() . 'upload/' . $v->images;
                }
            }
            if (!empty($v->detail_images)) {
                $res = $v->detail_images;
                $v->detail_images = $tool->addHostToImage($res);
            }
        }
        if (!empty($data)) {
            $list =  $data->toArray();
            if(empty($param['views']) && empty($param['news']) && isset($param['is_distance']) &&  $param['is_distance'] ==1){
                //附近商家排序
//                $last_names = array_column($list['data'],'distance');
                //dd($last_names);
//                array_multisort($last_names,SORT_ASC,$list['data']);
                array_multisort(array_column($list['data'],'distance'), SORT_ASC, $list['data']);
                //距离添加单位
                foreach($list['data'] as &$v){
                    $v['distance'] = $v['distance']."km";
                }
                return $list;
            }else{
                foreach($list['data'] as &$v){
                    $v['distance'] = $v['distance']."km";
                }
            }
            return $list;
        } else {
            return [];
        }
    }

    /**
     * @param $id
     * @return mixed
     * 编辑使用
     */
    public function getInfoEdit($id)
    {
        return $this->where([['id', '=', $id]])->first();
    }
    

    /**
     * @param $id
     * @return mixed
     * 查询商户信息
     */
    public function getInfo($id)
    {
        $res = $this->where([['id', '=', $id]])->with(['shoptypes'])->first();
        if(!$res){
            return false;
        }
        $host = new Url();
        $tool = new Tool();
        if (!empty($res->logo)) {
            $res->logo = $host::getHttpHost() . 'upload/' . $res->logo;
        }
        if (!empty($res->business_license)) {
            $res->business_license = $host::getHttpHost() . 'upload/' . $res->business_license;
        }
        if (!empty($res->images)) {
            $res->images = $tool->addHostToImage($res->images);
        }
        if (!empty($res->detail_images)) {
            $res->detail_images = $tool->addHostToImage($res->detail_images);
        }
        $res->increment("views",1);
//        $res['images'] = env("APP_URL") . '/upload/' . $res['images'];
//        $res['detail_images'] = unserialize($res['detail_images']);
//        if (is_array($res['detail_images'])) {
//            foreach ($res['detail_images'] as $kk => $vv) {
//                $res['detail_images'][$kk] = env("APP_URL") . '/upload/' . $vv;
//            }
//        }
        return $res;
    }


    /**
     * @param $data
     * 添加商圈订单
     */
    public function addStoreOrder($data)
    {
        $store_order = new StoreOrder();
        $store_order->sn = $this->storeOrderNumber();
        $store_order->user_id = $data['user_id'];
        $store_order->store_id = $this->id;
        $store_order->save();
        return $store_order->id;
    }


    /****
     * @return string
     * 订单号生成
     */
    public function storeOrderNumber()
    {
        return "st_".date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }


    public function pay($res)
    {
       $pay_type =  (new StorePayType())->where([['id','=',$res['type_id']]])->first();
       $store_order = (new StoreOrder())->where([['id','=',$res['store_order_id']]])->first();
       $store_detail = $this->where([['id','=',$store_order->store_id]])->first();
       $store_order->money = $pay_type->money;
       $store_order->type = $pay_type->type;
       $store_order->days = $pay_type->days;
       $store_order->pay_type = $res['pay_type'];
       $store_order->type_id = $res['type_id'];
       $store_order->save();
       if($res['pay_type'] ==1){  //微信支付
           $data['sn'] = $store_order->sn;
           $data['des'] = '100_益鹿出院-商圈订单支付';
           $data['price'] = $pay_type->money;
           if($pay_type->money == 0){
               $store_order_dt = new StoreOrder();
               $lit['order_status'] = 1;
               $lit['pay_status'] = 1;
               $lit['pay_time'] = date("Y-m-d H:i:s", time());
               $store_order_dt->where([['id', '=', $res['store_order_id']]])->update($lit);
               (new Store())->where([['id','=',$store_order->store_id]])->update(['topping' => $store_order->type, 'buy_type' => $store_order->type_id, "is_online" => 1]);
               return ["result"=>"success"];
           }
           $res = (new WxPayController())::setPay($data);
           return $res;
       }elseif ($res['pay_type'] ==2){  //支付宝
           $datas['sn'] = $store_order->sn;
           $datas['pay_price'] = $pay_type->money;
           $datas['user_id'] = $store_order->user_id;
           $datas['subject'] = '100_'.$store_detail->shop_name .'商圈支付';
           if($pay_type->money == 0){
                $store_order_dt = new StoreOrder();
                $lit['order_status'] = 1;
                $lit['pay_status'] = 1;
                $lit['pay_time'] = date("Y-m-d H:i:s", time());
                $store_order_dt->where([['id', '=', $res['store_order_id']]])->update($lit);
                (new Store())->where([['id','=',$store_order->store_id]])->update(['topping' => $store_order->type, 'buy_type' => $store_order->type_id, "is_online" => 1]);
                return "success";
            }
           $res = (new PaymentController())->doPay($datas);
           return $res;
       }

    }

}
